﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using System.Web.UI;
using zyconfig;
using zymarc;
using System.Threading;
using ToolUtil;
using MTOM_Library.MtomWebService;
using MTOM_Library;
using System.Net;
using System.Media;
using zymain.Properties;
using UploadWinClient;

namespace zymain
{
    public partial class FrmDigitalize : Form
    {
        private int kjm;
        public BindingSource BookData;
        public BindingSource FsData;
        private bool flag;
        private string mainKay = string.Empty;
        private OpenFileDialog openUpLoad = new System.Windows.Forms.OpenFileDialog();
        private string uid;
        private UploadFiles up;
        public static MTOMWse WebService;
        private bool ftpFull=false;
        private int usType = 2;
        public FrmDigitalize()
        {
            InitializeComponent();
        }

        private void FrmDigitalize_Load(object sender, EventArgs e)
        {
            WebService = new MTOMWse();
            string formName = "FrmTool";
            Form fr = System.Windows.Forms.Application.OpenForms[formName];
            if (fr != null)
            {
                FrmTool f1 = (FrmTool)fr;
                //取到Form1的值是1
                this.uid = f1.UserID;
            }
            this.openUpLoad.Multiselect = true;
            this.openUpLoad.Title = "请选择你要上次的文件";
            this.workerGetFileList.RunWorkerAsync();
            this.workerFtp.RunWorkerAsync();
            this.taskPanel1.RemoveItemsWhenFinished = true;
            this.taskPanel1.RemoveItemsOnError = false;
            this.taskPanel1.AutoSizeForm = false;
            this.dudMaxThreads_ValueChanged(sender, e);
            this.MarcRadio();
        }
        private void MarcRadio()
        {
            foreach (System.Windows.Forms.Control c in usPanel.Controls)
            {
                if (c is RadioButton)
                {
                    if (((RadioButton)c).Checked)
                    {
                        usType = ((RadioButton)c).TabIndex;
                    }
                }
            }
        }
        private void dudMaxThreads_ValueChanged(object sender, EventArgs e)
        {
            ThreadPool.SetMaxThreads((int)this.dudMaxThreads.Value, (int)this.dudMaxThreads.Value);
        }

        private bool AuthenticateWebService()
        {
            if ((WebService.CookieContainer != null) && (WebService.CookieContainer.Count > 0))
            {
                return true;
            }
            try
            {
                string str = string.Format("?Username={0}&Password={1}", this.txtUsername.Text, this.txtPassword.Text);
                //Console.WriteLine(WebService.Url.Replace("MTOM.asmx", "") + "Login.aspx" + str);
                HttpWebRequest request = WebRequest.Create(WebService.Url.Replace("MTOM.asmx", "") + "Login.aspx" + str) as HttpWebRequest;
                request.CookieContainer = new CookieContainer();
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                WebService.CookieContainer = request.CookieContainer;
                return (response.Cookies.Count > 0);
            }catch(WebException ex)
            {
                //Console.WriteLine(ex.Message);
                return false;
            }
        }

        private void digitalize_btnScarchClick(object sender, EventArgs e)
        {
            this.Invalidate();
            this.kjm = this.mainSearch1._kjm;
            this.Cursor = Cursors.WaitCursor;
            string sql = this.mainSearch1.Sql;
            this.BookData = new BindingSource();
            DataTable dt = new DataTable();
            using (DbOperHandler _open = new Common().Doh())
            {
                if (_open.dbType.ToString().Equals("ORACLE") || _open.odbType.ToString().Equals("ORACLE"))
                    flag = true;
                _open.Reset();
                _open.SqlCmd = sql;
                //Console.WriteLine(sql);
                dt = _open.GetDataTable();
                //d1 = DTable.TrimValueForOutPut(dt);
                var dataRows = dt.AsEnumerable();
                foreach (var row in dataRows)
                {
                    var cellList = row.ItemArray.ToList();
                    row.ItemArray = cellList.Select(x => x.ToString().Trim()).ToArray();
                }
                this.dataGridBook.Columns.Clear();
                this.dataGridBook.AutoGenerateColumns = true;
                this.BookData.DataSource = dt;
                this.binNavBook.BindingSource = this.BookData;
                this.BookData.PositionChanged += new EventHandler(this.BookData_PositionChanged);
                this.dataGridBook.DataSource = this.BookData;
                this.dataGridBook.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);//宽度自适应
                //this.dataGridBook.Columns.Remove(this.dataGridBook.Columns[this.dataGridBook.ColumnCount - 1]);
                if (this.BookData.Count == 0)
                {
                    MessageBox.Show("未检索到任何记录");
                    this.cisoBtn.Enabled = false;
                    this.uqtBtn.Enabled = false;
                }
                else
                {
                    this.BookData_PositionChanged(sender, e);
                    this.cisoBtn.Enabled = true;
                    this.uqtBtn.Enabled = true;
                }
            }
            //Console.WriteLine(sql);
            this.Cursor = Cursors.Default;
        }
        private void BookData_PositionChanged(object sender, EventArgs e)
        {
            DataRowView current = this.BookData.Current as DataRowView;
            if (current != null)
            {
                mainKay = current["主键码"].ToString().Trim();
                using (DbOperHandler _open = new Common().Doh())
                {
                    _open.Reset();
                    _open.ConditionExpress = " 库键码=" + this.kjm;
                    int mlx = Convert.ToInt32(_open.GetField("书目数据库定义", "MARC类型").ToString().Trim());
                    this.marcGridS1.kjm = this.kjm.ToString();
                    this.marcGridS1.MarcType = mlx;
                    _open.Reset();
                    _open.ConditionExpress= "主键码=" + mainKay;
                    string marc = _open.GetField("情报检索库", "marc").ToString();
                    MarcConvert convert = new MarcConvert();
                    try
                    {
                        convert.ISOData = marc;
                        convert.SetISOtoMarc();
                    }
                    catch
                    {
                        convert.MarcText = marc;
                    }
                    this.marcGridS1.MarcText = convert.MarcText;
                    this.marcGridS1.SetGridView();
                    if (this.mainSearch1.fsFull)
                    {
                        _open.Reset();
                        _open.SqlCmd = "select * from DISK_情报检索文件信息表 where 主键码=" + mainKay;
                        DataTable dt = _open.GetDataTable();
                        this.FsData = new BindingSource();
                        this.dataGridView1.AutoGenerateColumns = true;
                        this.FsData.DataSource = dt;
                        this.dataGridView1.DataSource = this.FsData;
                        if (this.FsData.Count > 0)
                            this.BuindFildTypeImg();
                    }                    
                }
            }
        }

        private void BuindFildTypeImg()
        {
            for (int i = 0; i <= (this.dataGridView1.RowCount - 1); i++)
            {
                string str = this.dataGridView1.Rows[i].Cells["ColType"].Value.ToString();
                str = str.Replace(".", "");
                if (str.ToUpper() == "DOC")
                {
                    this.dataGridView1.Rows[i].Cells["ImgFile"].Value = Resources.word;
                }
                if (str.ToUpper() == "PDF")
                {
                    this.dataGridView1.Rows[i].Cells["ImgFile"].Value = Resources.pdf;
                }
                if (str.ToUpper() == "XLS")
                {
                    this.dataGridView1.Rows[i].Cells["ImgFile"].Value = Resources.xls;
                }
                if (str.ToUpper() == "PPT")
                {
                    this.dataGridView1.Rows[i].Cells["ImgFile"].Value = Resources.ppt;
                }
                if (str.ToUpper() == "TXT")
                {
                    this.dataGridView1.Rows[i].Cells["ImgFile"].Value = Resources.txt;
                }
                if (str.ToUpper() == "RAR")
                {
                    this.dataGridView1.Rows[i].Cells["ImgFile"].Value = Resources.rar;
                }
                if (str.ToUpper() == "ISO")
                {
                    this.dataGridView1.Rows[i].Cells["ImgFile"].Value = Resources.Iso;
                }
                if (str.ToUpper() == "JPG")
                {
                    this.dataGridView1.Rows[i].Cells["ImgFile"].Value = Resources.pic;
                }
                if (str.ToUpper() == "GIF")
                {
                    this.dataGridView1.Rows[i].Cells["ImgFile"].Value = Resources.pic;
                }
                if (str.ToUpper() == "ZIP")
                {
                    this.dataGridView1.Rows[i].Cells["ImgFile"].Value = Resources.Zip;
                }
            }
        }
        private void Frm_Shown(object sender, EventArgs e)
        {
            this.mainSearch1.AddConfig(0, null);
        }

        private void excelItem_Click(object sender, EventArgs e)
        {

        }
        /// <summary>
        /// 创建ISO
        /// </summary>
        private void dqisoItem_Click(object sender, EventArgs e)
        {
            FrmMakeISO eiso = new FrmMakeISO();
            if (eiso.ShowDialog() == DialogResult.OK)
            {
                if (usType == 0)
                {
                    this.AddFileUpLoad(eiso.FilePath, mainKay);
                }
                if (usType == 1)
                {
                    this.up = new UploadFiles(this.uid, this.Name);
                    this.up.AddFileUpLoad("2", eiso.FilePath, mainKay);
                }
            }
        }
        public void AddFileUpLoad(string FilePath, string MainKay)
        {
            string guid = Guid.NewGuid().ToString();
            string kzName = Path.GetExtension(FilePath).ToUpper().Replace(".", "");
            string fileName = Path.GetFileName(FilePath);
            //ControlLog.AddCreateISOLog(this.uid, fileName, MainKay);
            if (FileFunction.InsertInfor("2",MainKay, kzName, fileName, this.uid, FilePath, guid))
            {
                this.taskPanel1.AddOperation(new TaskPanelOperation(guid, $"上传: {Path.GetFileName(FilePath)}", ProgressBarStyle.Blocks));
                ThreadPool.QueueUserWorkItem(new WaitCallback(this.MtomUpFile), new Triplet(guid, FilePath, 0));
            }
            else
            {
                MessageBox.Show("添加信息到数据库失败！无法上传文件,请检查...", "提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }
        private void MtomUpFile(object triplet)
        {
            string str = (triplet as Triplet).First.ToString();
            string str2 = (triplet as Triplet).Second.ToString();
            long argument = long.Parse((triplet as Triplet).Third.ToString());
            FileTransferUpload upload = new FileTransferUpload();
            upload.WebService.CookieContainer = WebService.CookieContainer;
            upload.Guid = str;
            if (this.chkAutoChunksize.Checked)
            {
                upload.AutoSetChunkSize = true;
            }
            else
            {
                upload.AutoSetChunkSize = false;
                upload.ChunkSize = ((int)this.dudChunkSize.Value) * 0x400;
            }
            upload.LocalFilePath = str2;
            upload.IncludeHashVerification = this.chkHash.Checked;
            upload.ProgressChanged += new ProgressChangedEventHandler(this.ft_ProgressChanged);
            upload.RunWorkerCompleted += new RunWorkerCompletedEventHandler(this.ft_RunWorkerCompleted);
            upload.RunWorkerSync(new DoWorkEventArgs(argument));
        }
        private void ft_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            this.taskPanel1.ProgressChanged((sender as FileTransferBase).Guid, e.ProgressPercentage, e.UserState.ToString());
        }
        private void ft_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            string guid = (sender as FileTransferBase).Guid;
            if (e.Error != null)
            {
                this.taskPanel1.EndOperation(guid, e.Error);
            }
            else if (e.Cancelled)
            {
                this.taskPanel1.EndOperation(guid, new Exception("Cancelled"));
            }
            else
            {
                this.taskPanel1.EndOperation(guid, null);
                if (this.taskPanel1.List.Count == 0)
                {
                    this.Ding();
                }
                string filePath = string.Empty;
                string mainKay = FileFunction.GetMainKay("2",guid, out filePath);
                ControlLog.AddUpLoadLog("2",this.uid, filePath, mainKay);
                if (!FileFunction.UpdateSucess("2",guid, this.uid))
                {
                    MessageBox.Show("更新上传库信息失败！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
                else if (DbConfig.DelOnUpLoadSucess == "1")
                {
                    DeleteFile file = new DeleteFile(guid,"2");
                    new Thread(new ThreadStart(file.DoWork)).Start();
                }
            }
        }
        private void Ding()
        {
            try
            {
                SoundPlayer player = new SoundPlayer();
                player.Stream = base.GetType().Assembly.GetManifestResourceStream("UploadWinClient.download_complete.wav");
                player.Play();
            }
            catch
            {
            }
        }
        /// <summary>
        ///  上传ISO
        /// </summary>
        private void uisoItem_Click(object sender, EventArgs e)
        {
            this.openUpLoad.Filter = "可以上传的文件|*.iso|所有类型文件|*.*";
            if ((this.openUpLoad.ShowDialog() == DialogResult.OK) && (MessageBox.Show("确认要上传选定的文件吗？", "询问", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.OK))
            {
                if (this.usType == 1)
                {
                    this.up = new UploadFiles(this.uid, this.Name);
                    FrmUpProgess progess = new FrmUpProgess();
                    foreach (string str in this.openUpLoad.FileNames)
                    {
                        progess.Show();
                        progess.label1.Text = "当前文件:" + str;
                        string extension = Path.GetExtension(str);
                        string eFileName = DateTime.Now.ToString("yyyyMMddhhmmss") + extension;
                        eFileName = DbConfig.WorkDir + eFileName;
                        FileTool.CopyFilePro(str, eFileName, progess.progressBarX1);
                        progess.Close();
                        this.up.AddFileUpLoad("2", eFileName, mainKay);
                        Thread.Sleep(0x3e8);
                    }
                }
                if (usType == 0)
                {

                }
            }
        }

        private void btnTestAuth_Click(object sender, EventArgs e)
        {

        }

        private void workerGetFileList_DoWork(object sender, DoWorkEventArgs e)
        {
            bool f = this.AuthenticateWebService();
            if (f)
            {
                string[] filesList = WebService.GetFilesList();
                e.Result = filesList;
            }
            else
            {
                e.Cancel = true;
            }
        }

        private void workerFileHash_DoWork(object sender, DoWorkEventArgs e)
        {
            e.Result = FileTransferBase.CalcFileHash(e.Argument.ToString());
        }

        private void workerFileHash_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            this.lblErrors.Text = "[Hash copied to clipboard]: " + e.Result.ToString();
            Clipboard.SetData(DataFormats.StringFormat, e.Result.ToString());
            this.toolStripStatusLabel1.Text = "Ready";
            this.Cursor = Cursors.Default;
        }

        private void workerGetFileList_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled)
            {
                this.lblErrors.Text = "MTOM服务端连接失败";
                this.mtomRadio.Enabled = false;
            }
            else
            {
                if (e.Error != null)
                {
                    this.mtomRadio.Enabled = false;
                    if (e.Error.Message.Contains("ReturnUrl=") || e.Error.Message.Contains("forcibly closed"))
                    {
                        this.lblErrors.Text = "Forms Authentication Required";
                        this.chkLoginRequired.Checked = true;
                        this.txtUsername.Focus();
                    }
                    else
                    {
                        this.lblErrors.Text = "Could not list files on server: " + e.Error.Message;
                    }
                }
                else
                {
                    this.mtomRadio.Enabled = true;
                    this.mtomRadio.Checked = true;
                    this.lblErrors.Text = "";
                    this.lstDownloadFiles.Items.Clear();
                    foreach (string str in e.Result as string[])
                    {
                        this.lstDownloadFiles.Items.Add(str);
                    }
                }
            }
            
        }

        private void autoCHunk_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox checkBox = sender as CheckBox;
            if (checkBox.Checked)
            {
                this.dudChunkSize.Enabled = false;
            }
            else
            {
                this.dudChunkSize.Enabled = true;
            }
        }

        private void chkLogin_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox checkBox = sender as CheckBox;
            if (checkBox.Checked)
            {
                this.txtUsername.Enabled = true;
                this.txtPassword.Enabled = true;
            }
            else
            {
                this.txtUsername.Enabled = false;
                this.txtPassword.Enabled = false;
            }
        }

        private void workerFTP_DoWork(object sender, DoWorkEventArgs e)
        {
            ftpFull = FileTool.CheckFTP(DbConfig.FtpAddress, DbConfig.FtpUser, DbConfig.FtpPass, Convert.ToInt32(DbConfig.FtpPort));
            if (!ftpFull)
            {
                this.ftpRadio.Enabled = false;
                e.Cancel = true;
            }
            else
            {
                this.ftpRadio.Enabled = true;
            }

        }

        private void workerFTP_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled)
            {
                this.lblErrors.Text = "FTP服务端连接失败";
            }
            else
                this.lblErrors.Text = "";
        }
        /// <summary>
        /// 全部记录创建ISO
        /// </summary>
        private void alluisoItem_Click(object sender, EventArgs e)
        {
            for(int i = 0; i < this.dataGridBook.Rows.Count; i++)
            {
                string kay = this.dataGridBook.Rows[i].Cells["主键码"].Value.ToString().Trim();
                FrmMakeISO eiso = new FrmMakeISO();
                if (eiso.ShowDialog() == DialogResult.OK)
                {
                    if (usType == 0)
                    {
                        this.AddFileUpLoad(eiso.FilePath, kay);
                    }
                    if (usType == 1)
                    {
                        this.up = new UploadFiles(this.uid, this.Name);
                        this.up.AddFileUpLoad("2", eiso.FilePath, kay);
                    }
                }
            }
        }

        private void alluqtItem_Click(object sender, EventArgs e)
        {

        }

        private void dquqtItem_Click(object sender, EventArgs e)
        {

        }
    }
}
